package com.hanser.hancoder.langgraph4j.tool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hanser.hancoder.langgraph4j.model.ImageResource;
import com.hanser.hancoder.langgraph4j.model.enums.ImageCategoryEnum;
import dev.langchain4j.agent.tool.P;
import dev.langchain4j.agent.tool.Tool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Component
public class UndrawIllustrationTool {

    private static final String UNDRAW_BASE_URL = "https://undraw.co/search/%s";

    @Tool("搜索插画图片，用于网站美化和装饰")
    public List<ImageResource> searchIllustrations(@P("搜索关键词") String query) {
        List<ImageResource> imageList = new ArrayList<>();
        String requestUrl = String.format(UNDRAW_BASE_URL, query);

        try (HttpResponse response = HttpRequest.get(requestUrl).timeout(10000).execute()) {
            if (!response.isOk()) {
                log.error("请求失败，状态码：{}", response.getStatus());
                return imageList;
            }

            String htmlBody = response.body();
            String jsonData = extractNextData(htmlBody);

            if (StrUtil.isBlank(jsonData)) {
                log.warn("未找到 __NEXT_DATA__");
                return imageList;
            }

            JSONObject result = JSONUtil.parseObj(jsonData);
            JSONObject pageProps = result.getJSONObject("props").getJSONObject("pageProps");
            if (pageProps == null) {
                return imageList;
            }

            JSONArray initialResults = pageProps.getJSONArray("initialResults");
            if (initialResults == null || initialResults.isEmpty()) {
                return imageList;
            }

            for (JSONObject illustration : initialResults.jsonIter()) {
                String title = illustration.getStr("title", "插画");
                String media = illustration.getStr("media", "");
                if (StrUtil.isNotBlank(media)) {
                    imageList.add(ImageResource.builder()
                            .category(ImageCategoryEnum.ILLUSTRATION)
                            .description(title)
                            .url(media)
                            .build());
                }
            }
        } catch (Exception e) {
            log.error("搜索插画失败：{}", e.getMessage(), e);
        }

        return imageList;
    }

    /**
     * 从 HTML 内容中提取 __NEXT_DATA__ 的 JSON 字符串
     *
     * @param html HTML 网页内容
     * @return 提取出的 JSON 字符串，如果未找到则返回空字符串
     */
    private String extractNextData(String html) {
        Pattern pattern = Pattern.compile("<script id=\"__NEXT_DATA__\" type=\"application/json\">(.*?)</script>");
        Matcher matcher = pattern.matcher(html);
        if (matcher.find()) {
            return matcher.group(1);
        }
        return "";
    }
}